package com.ruoyi.web.controller.pool;
import com.magus.OPException;
import com.magus.jdbc.OPResultSet;
import com.magus.jdbc.net.OPConf;
import com.magus.opio.net.IOPConnect;
import com.magus.opio.pool.OPConnectManage;
import java.sql.SQLException;

/**
 * @author 葛阳  1026094644@qq.com
 * @description 获取连接
 * @date 2023/2/1 15:41
 */
public class OPPool {

    private final static String IP = "192.168.2.76";//数据库IP
    private final static int PORT = 8200;//数据库端口
    private final static String USER = "sis";//数据库用户
    private final static String PWD = "openplant";//数据库密码
    private final static int MAX = 30;//连接池最大连接数
    private final static int MIN = 2;//连接池最小持有连接
    private static OPConnectManage manage;//连接池
    private final static int TIMEOUT = 120;//超时时间

    static {
        // 连接池配置信息
        OPConf config = new OPConf(IP,PORT,USER,PWD,true,TIMEOUT);
        // 实例化连接池
        manage = OPConnectManage.getInstance(config, MAX, MIN);
    }

    private OPPool() {
        // TODO Auto-generated constructor stub
    }


    /**
     * 获取连接
     * @return
     */
    public synchronized static IOPConnect getConn() {
        IOPConnect conn = null;
        try {
            conn = manage.getConnect();
        } catch (OPException e) {
            // TODO Auto-generated catch block
            System.out.println("获取连接出错！");
            e.printStackTrace();
        }
        return conn;

    }

    /**
     * 释放连接
     *
     * @param conn
     */
    public synchronized static void freeConn(IOPConnect conn) {

        try {
            manage.freeConnect(conn);
        } catch (OPException e) {
            // TODO Auto-generated catch block
            System.out.println("释放连接出错!");
            e.printStackTrace();
        }
    }

    /**
     * 关闭结果集，并释放连接
     *
     * @param conn
     * @param rs
     */
    public synchronized static void close(IOPConnect conn, OPResultSet rs) {

        try {
            if (null != rs) {
                rs.close();
            }
            manage.freeConnect(conn);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("关闭ResultSet失败！");
            e.printStackTrace();
        } catch (OPException e) {
            // TODO Auto-generated catch block
            System.out.println("连接释放失败！");
            e.printStackTrace();
        }

    }

}
